﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace WpfApp3
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class MainViewModel : ViewModelBase
    {
        private DownloadManager _downloadManager;
        private ObservableCollection<DownloadTask> _tasks;
        private double _totalProgress;

        public ObservableCollection<DownloadTask> Tasks
        {
            get => _tasks;
            set
            {
                _tasks = value;
                OnPropertyChanged();
            }
        }

        public double TotalProgress
        {
            get => _totalProgress;
            set
            {
                _totalProgress = value;
                OnPropertyChanged();
            }
        }

        private bool isTileView = true;
        public bool IsTileView
        {
            get { return isTileView; }
            set { isTileView = value; OnPropertyChanged(); }
        }


        public ICommand AddTaskCommand { get; }
        public ICommand CancelTaskCommand { get; }
        public ICommand RetryTaskCommand { get; }
        public ICommand DeleteTaskCommand { get; }
        public ICommand ClearTasksCommand { get; }
        public ICommand CancelAllTasksCommand { get; }
        public ICommand RetryAllTasksCommand { get; }
        public ICommand ListViewCommand { get; }

        public MainViewModel()
        {
            _downloadManager = new DownloadManager(3); // 设置并发数量
            _tasks = new ObservableCollection<DownloadTask>();

            _downloadManager.OnProgressChanged += progress => OnPropertyChanged(nameof(Tasks));
            _downloadManager.OnAllDownloadsCompleted += () =>
            {

                /* Handle all downloads completed */
            };

            AddTaskCommand = new RelayCommand(AddTask);
            CancelTaskCommand = new RelayCommand<DownloadTask>(CancelTask);
            RetryTaskCommand = new RelayCommand<DownloadTask>(RetryTask);
            DeleteTaskCommand = new RelayCommand<DownloadTask>(DeleteTask);
            ClearTasksCommand = new RelayCommand(ClearTasks);
            CancelAllTasksCommand = new RelayCommand(CancelAllTasks);
            RetryAllTasksCommand = new RelayCommand(RetryAllTasks);
            ListViewCommand = new RelayCommand(ListView);
            string path = Path.Combine(filePath, "CloudCfg.xml");
            string url = "http://39.98.179.209:8888/update/MedierCenter/newest/UpdateInfo";
            var clg = new DownloadTask(url, path, new HttpClient());
            clg.OnStatusChanged += (t) =>
            {
                if (t.Status == DownloadStatus.Completed)
                {
                    AddD(path);
                }
            };
            clg.StartAsync();
        }

        private async void AddD(string path)
        {
            var ServerCfg = await Task.Run(() => XmlHelper.DeserializeMethod<UpdaterModel>(path));
            string url = $"http://39.98.179.209:8888/update/MedierCenter/{ServerCfg.Version}/";
            foreach (var item in ServerCfg.Files)
            {
                var task = _downloadManager.AddTask(url + item.Name, Path.Combine(filePath, item.Name));
                // task.OnStatusChanged += Task_OnStatusChanged;

                Tasks.Add(task);
            }
        }



        string filePath = $"{AppDomain.CurrentDomain.BaseDirectory}Downloads";

        private void AddTask()
        {
            var rad = new Random();
            foreach (var item in CheckExtend.videoUrls)
            {
                var task = _downloadManager.AddTask(item, Path.Combine(filePath, rad.Next(100, 9999) + ".txt"));
                // task.OnStatusChanged += Task_OnStatusChanged;

                Tasks.Add(task);
            }
        }

        private void Task_OnStatusChanged(DownloadTask task)
        {
            // 通知 UI 更新
            // Application.Current.Dispatcher.Invoke(() =>
            //  {
            OnPropertyChanged(nameof(Tasks));
            // 在这里进行 UI 更新操作，例如触发 PropertyChanged
            // PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("YourPropertyName"));
            // });
        }

        private void ListView()
        {
            IsTileView = !IsTileView;
        }

        private void CancelTask(DownloadTask task)
        {
            _downloadManager.CancelTask(task.Id);
        }

        private void RetryTask(DownloadTask task)
        {
            _downloadManager.RetryTask(task.Id);
        }

        private void DeleteTask(DownloadTask task)
        {
            _downloadManager.DeleteTask(task.Id);
            Tasks.Remove(task);
        }

        private void ClearTasks()
        {
            _downloadManager.DeleteTask();
            Tasks.Clear();
        }

        private void CancelAllTasks()
        {
            _downloadManager.CancelTask();
        }

        private void RetryAllTasks()
        {
            _downloadManager.RetryTask();
        }
    }
}
